package com.lhys.controller;

import com.lhys.common.ApiResultMsg;
import com.lhys.common.ResultInfo;
import com.lhys.controller.base.BaseController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.Authorization;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 * User: xiaoqi
 * Date: 2021-06-21
 * Time: 下午 17:42
 * Description: 文件上传控制器
 */
@RestController
@Api(tags = "文件上传模块")
@RequestMapping("/api/file")
public class FileController extends BaseController {

    @PostMapping("/upload")
    @ApiOperation(value = "文件上传接口", authorizations = {@Authorization(value = header)})
    public ApiResultMsg upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            // 上传文件夹名字
            String rootPath = request.getSession().getServletContext().getRealPath("upload");
            // 上传文件新名字
            String newFileName = UUID.randomUUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 创建年月日文件夹
            Calendar date = Calendar.getInstance();
            // 日期文件夹
            File dateDir = new File(date.get(Calendar.YEAR) + File.separator + (date.get(Calendar.MONTH) + 1));
            // 新文件
            File newFile = new File(rootPath + File.separator + dateDir + File.separator + newFileName);
            // 判断新文件的父级目录是否存在
            if (!newFile.getParentFile().exists()) {
                // 不存在 创建
                newFile.getParentFile().mkdirs();
            }
            file.transferTo(newFile);
            // 新文件url
            String fileUrl = date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH) + 1) + "/" + newFileName;
            HashMap<String, Object> map = new HashMap<>();
            map.put("name", newFileName);
            map.put("url", "/upload/" + fileUrl);
            System.out.println(newFile.getPath());
            System.out.println(newFile.getAbsolutePath());
            return ApiResultMsg.success(200, "上传成功", map);
        } catch (IOException e) {
            e.printStackTrace();
            return ApiResultMsg.error("上传失败");
        }
    }

}